package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yzdbx.task.ProductOrderRunnable.GEN_LLD_IDS;
import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getById;
import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_DATE;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: 生产领料出库
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class LLOutRunnable implements Exe {


    private Connection connection;


    public LLOutRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        List<Integer> lldIds = GEN_LLD_IDS.get();

        if (CollectionUtil.isEmpty(lldIds))
            return Boolean.TRUE;
        try {
            PreparedStatement prepared = connection.prepareStatement("select * from lists where cashiersNumber like concat(?,'%') order by cashiersNumber desc limit 1");
            prepared.setString(1, "CK"+CUR_DATE.get().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            List<LinkedHashMap<String, Object>> linkedHashMaps = DbUtil.resultSetToList(prepared.executeQuery());
            Long num = 0L;
            if (CollectionUtil.isNotEmpty(linkedHashMaps)) {
                num = Long.parseLong(linkedHashMaps.get(0).get("cashiersNumber").toString().replace("CK", ""));
            }
            int ckId = getMaxId(connection, "lists");
            int ckDetailId = getMaxId(connection, "ck02CheckoutFormCheckout");
            List<LinkedHashMap<String, Object>> sc01ProductionPlans = DbUtil.resultSetToList(connection.prepareStatement("select * from sc01ProductionPlan").executeQuery());
            for (Integer lldId : lldIds) {
                Map<String, Object> lld = DbUtil.getById(connection, "itsACollarList", lldId);


                PreparedStatement statement = connection.prepareStatement("insert into lists(id,cashiersNumber,poolType,collectionDate,operator,clientInformation,associatedOrders)values (?,?,?,?,?,?,?)");
                statement.setInt(1, ++ckId);
                statement.setString(2, "CK" + (++num));
                statement.setString(3, "领料出库");
                Object dateObj = lld.get("f775");
                java.sql.Date sqlDate;
                if (dateObj instanceof Timestamp) {
                    sqlDate = new java.sql.Date(((Timestamp) dateObj).getTime());
                } else if (dateObj instanceof java.sql.Date) {
                    sqlDate = (java.sql.Date) dateObj;
                } else {
                    throw new RuntimeException("Unsupported date type: " + dateObj.getClass().getName());
                }
                statement.setDate(4, sqlDate);
                statement.setString(5, lld.get("theLeadman").toString());
                int associatedOrders = (int) lld.get("associatedOrders");
                Map<String, Object> productionPlan = sc01ProductionPlans.stream().filter(map -> ObjectUtil.equal(map.get("id"), associatedOrders)).findFirst().get();
                statement.setInt(6, ((int) productionPlan.get("clientName")));
                statement.setInt(7, associatedOrders);
                statement.execute();

                statement = connection.prepareStatement("select * from checklistOfTheCollar where f8d0 = ?");
                statement.setInt(1, lldId);
                List<LinkedHashMap<String, Object>> lldDetailList = DbUtil.resultSetToList(statement.executeQuery());
                for (LinkedHashMap<String, Object> lldDetail : lldDetailList) {
                    statement = connection.prepareStatement("insert into ck02CheckoutFormCheckout(id,productInformation,numberOfReleases,inventoryUnitPrice,linkOutList,synchronisingFolderFailedSS,modifyer,created,modified)values (?,?,?,?,?,?,?,?,?)");
                    statement.setInt(1, ++ckDetailId);
                    int materialInformation = Integer.parseInt(lldDetail.get("materialInformation").toString());
                    statement.setInt(2, materialInformation);
                    BigDecimal number = (BigDecimal) lldDetail.get("number");
                    statement.setBigDecimal(3, number);
                    statement.setBigDecimal(4, RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)));
                    statement.setInt(5, ckId);
                    statement.setString(6, lld.get("theLeadman").toString());
                    statement.setString(7, lld.get("theLeadman").toString());
//                    statement.setDate(8, new Date(((Timestamp) lld.get("f775")).getTime()));
//                    statement.setDate(9, new Date(((Timestamp) lld.get("f775")).getTime()));
                    statement.setDate(8, sqlDate);
                    statement.setDate(9, sqlDate);
                    statement.execute();
                }

            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        return Boolean.TRUE;
    }

    private java.sql.Date getSqlDate(Object dateObj) {
        if (dateObj instanceof Timestamp) {
            return new java.sql.Date(((Timestamp) dateObj).getTime());
        } else if (dateObj instanceof java.sql.Date) {
            return (java.sql.Date) dateObj;
        } else {
            throw new RuntimeException("Unsupported date type: " + dateObj.getClass().getName());
        }
    }
}
